#!/bin/bash

set -e

NGINX_VERSION=1.22.1
INSTALL_DIR=/opt/nginx
SYMLINK_PATH=/usr/local/bin/nginx
NGINX_TAR=nginx-$NGINX_VERSION.tar.gz
NGINX_SRC_DIR=nginx-$NGINX_VERSION

echo "📦 开始安装 Nginx $NGINX_VERSION ..."

# 1. 检测系统类型
if [ -f /etc/redhat-release ]; then
    OS="centos"
elif [ -f /etc/lsb-release ] || grep -qi ubuntu /etc/os-release; then
    OS="ubuntu"
elif grep -qi debian /etc/os-release; then
    OS="debian"
else
    echo "❌ 不支持的系统，请手动安装依赖包。"
    exit 1
fi

echo "🖥 检测到系统类型：$OS"

# 2. 安装依赖
echo "🔧 安装构建依赖..."
if [ "$OS" == "centos" ]; then
    yum -y install gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel wget
elif [ "$OS" == "ubuntu" ] || [ "$OS" == "debian" ]; then
    apt-get update
    apt-get install -y build-essential libpcre3 libpcre3-dev zlib1g-dev libssl-dev wget
fi

# 3. 下载 & 解压源码
cd ~
if [ ! -f "$NGINX_TAR" ]; then
    wget http://nginx.org/download/$NGINX_TAR
fi
tar -zxvf $NGINX_TAR
rm -rf ~/nginx
mv $NGINX_SRC_DIR nginx
cd nginx

# 4. 配置编译选项
echo "⚙️ 配置编译选项..."
./configure --prefix=$INSTALL_DIR \
    --with-http_stub_status_module \
    --with-http_ssl_module \
    --with-http_gzip_static_module

# 5. 编译并安装
echo "🔨 编译并安装..."
make
make install

# 6. 创建软链接
echo "🔗 创建 nginx 命令软链接..."
ln -sf $INSTALL_DIR/sbin/nginx $SYMLINK_PATH

# 7. 修改配置避免 403（user root）
echo "🛠 修改 nginx.conf 启动用户为 root..."
sed -i 's/^user .*/user root;/' $INSTALL_DIR/conf/nginx.conf || echo "user root;" >> $INSTALL_DIR/conf/nginx.conf

# 8. 启动 nginx
echo "🚀 启动 nginx..."
nginx

echo "🎉 Nginx 安装成功，版本信息如下："
nginx -v